<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Exception;

/**
 * 题目管理
 * @icon fa fa-circle-o
 */
class Question extends Backend
{

    /**
     * Question模型对象
     * @var \app\admin\model\Question
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Question;
        $this->view->assign("kindList", $this->model->getKindList());
        $this->view->assign("difficultyList", $this->model->getDifficultyList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }




    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['mock'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('mock')->visible(['name']);
            }
            $count = $list->total();
            $items = $list->items();
            // 检测是否有重复题目
            foreach ($items as &$question) {
                $title = str_replace(' ', '', $question['title']);;
                $question['is_repeat'] = 0;

                foreach ($items as $item) {
                    if ($item['id'] != $question['id']) {
                        $title2 = str_replace(' ', '', $item['title']);
                        if ($title == $title2) {
                            // 标记重复
                            $question['is_repeat'] = 1;
                            break;
                        }
                    }
                }

                # 查询这个题目考点
                $examination_point = Db::name('examination_point')->whereIn('id', $question['examination_point_ids'])->select();
                if ($examination_point) {
                    $question['examination_point_names'] = implode(',', array_column((array)$examination_point, 'name'));
                }else{
                    $question['examination_point_names'] = '';
                }
            }
            $result = array("total" => $count, "rows" => $items);
            return json($result);
        }
        $question_menu_id = $this->request->get('question_menu_id', 0);
        $this->assign("question_menu_id", $question_menu_id);
        return $this->view->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            // if ($params['options_extend']) {
            //     $params['options_extend'] = json_decode(urldecode($params['options_extend']), true);
            // }
            // dd($params);

            $params['is_material_child'] = '0'; //默认都不是材料题
            if ($params) {
                $params = $this->preExcludeFields($params);
                // 检查题目输入
                $this->checkTitle($params);
                // 检查答案输入
                $this->checkAnswer($params);
                // 处理选项图片链接域名
                $this->optionsImage($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);

                    //                    // 保存材料题父题目
                    //                    $this->saveMaterialParentQuestion($this->model);
                    //                    // 保存材料题子题目
                    //                    $this->saveMaterialQuestions($this->model, $params['material_questions'] ?? []);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 处理选项图片链接域名
     * @param $data
     */
    protected function optionsImage(&$data)
    {
        $options_img = $data['options_img'] ?? [];
        $options_img = json_decode($options_img, true);
        if ($options_img) {
            foreach ($options_img as &$item) {
                if (strpos($item['value'], '://') === false) {
                    $item['value'] = cdnurl($item['value'], true);
                }
            }
        }
        $data['options_img'] = json_encode($options_img);
        $data['options_img'] = $data['options_img'] == 'null' ? [] : $data['options_img'];
    }


    /**
     * 检查题目内容输入
     * @param $params
     */
    protected function checkTitle(&$params)
    {
        if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
            if (!($params['title'] ?? '')) {
                $this->error('请输入题目内容');
            }
        } else if ($params['kind'] == 'FILL') {
            if (!($params['title_fill'] ?? '')) {
                $this->error('请输入填空题题目内容');
            }
            $params['title'] = $params['title_fill'];
        }

        // 替换题目图片CDN链接
        $params['title'] = replaceImgUrl($params['title']);
    }


    protected function checkAnswer(&$params)
    {
        $answer = $params['answer'] ?? '';
        $options = $params['options_json'] ?? [];

        if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
            if (!$answer) {
                $this->error('请设置题目答案');
            }
            if (!$options) {
                $this->error('请设置题目选项');
            }

            $options = json_decode($options, true);
            $option_keys = array_keys($options);

            // 多选题
            if (strpos($answer, ',') !== false) {
                $answer_arr = explode(',', trim($answer));
                foreach ($answer_arr as $item) {
                    if (!in_array($item, $option_keys)) {
                        $this->error('答案设置有误，答案选项不存在');
                    }
                }
            } else {
                if (!in_array($answer, $option_keys)) {
                    $this->error('答案设置有误，答案选项不存在');
                }
            }
        }

        // 后期拓展题型
        switch ($params['kind']) {
            // 填空题
            case 'FILL':
                if (!is_array($answer) || !count($answer)) {
                    $this->error('未设置填空题答案，至少设置一个');
                }

                // 转json
                $params['answer'] = json_encode($params['answer'], JSON_UNESCAPED_UNICODE);
                break;

            // 简答题
            case 'SHORT':
                $answer = $params['short_answer'] ?? '';
                if (!$answer) {
                    $this->error('请设置简答题标准答案');
                }
                $answer_config = $params['answer_config'] ?? [];
                if (!$answer_config) {
                    $this->error('请设置简答题答案关键词');
                }
                foreach ($answer_config as &$item) {
                    if (!$item['answer']) {
                        $this->error('简答题答案关键词不能为空');
                    }
                    //                    if (!is_numeric($item['score']) || $item['score'] < 0) {
                    //                        $this->error('简答题分数设置有误，必须为数字且不能小于0');
                    //                    }
                    $item['score'] = 0;
                }

                // 转json
                $params['answer'] = json_encode([
                    'answer' => $answer,
                    'config' => $answer_config
                ], JSON_UNESCAPED_UNICODE);
                break;

            // 材料题
            case 'MATERIAL':
                // dd([$params, $answer, $options]);

                if ($params['is_material_child']) {
                    $this->error('题型设置有误，材料题不能再设置为材料题的子题');
                }

                $params['is_material_child'] = 0;
                $params['material_question_id'] = 0;
                $params['material_questions'] = $params['material_questions'] ? json_decode($params['material_questions'], true) : [];
                if (!$params['material_questions']) {
                    if ($params['status'] == 'NORMAL') {
                        $this->error('请设置材料题的子题（或者状态先设置隐藏）');
                    }
                }
                // 转json
                $params['answer'] = json_encode([
                    'questions' => $params['material_questions']
                ], JSON_UNESCAPED_UNICODE);
                break;
        }
        if ($params['is_material_child']) {
            $params['material_question_id'] = $params['material_question_id'] ?? 0;
            if (!$params['material_question_id']) {
                $this->error('请设置材料题的父题');
            }
            if ($params['material_score'] <= 0) {
                $this->error('请设置材料题子题的分数');
            }
        }
    }

    /**
     * 选项图片页面
     * @return string
     */
    public function image()
    {
        if ($this->request->isPost()) {
            $this->success($this->request->post());
        }
        return $this->view->fetch();
    }

    public function select()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['mock'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
                $row->getRelation('mock')->visible(['name']);
            }
            $rows = $list->items();
            foreach ($rows as &$row) {
                $row['title'] = strip_tags($row['title']);
            }
            $result = array("total" => $list->total(), "rows" => $rows);
            return json($result);
        }
        return $this->view->fetch();
    }




    /**
     * Account:excel导入
     * User: Ixiangang
     * Date: 2025/6/4
     * Time: 17:16
     */
    public function importExcel()
    {
        if ($this->request->isPost()) {
            $mock_id = $this->request->param('mock_id');
            $examination_point_ids = $this->request->param('examination_point_ids');
            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }

            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }

            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }
            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    throw new \Exception(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow();        //取得一共有多少行
                $allRow = $currentSheet->getHighestRow();        //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields = [
                    'kind',
                    'title',
                    'explain',
                    'difficulty',
                    'answer',
                    'A',
                    'B',
                    'C',
                    'D',
                    'E',
                    'F',
                    'G',
                    'H',
                ];
                $time = time();
                $weigh = 1;
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = [];
                    $options = [];
                    // 选项及字段组合
                    for ($i = 0; $i < min($maxColumnNumber, count($fields)); $i++) {
                        $field = $fields[$i];
                        $value = $values[$i];
                        if ($i > 4) {
                            if (!empty($value) || $value == '0') {
                                $options[$field] = $value;
                            }
                        } else {
                            $row[$field] = $value;
                        }
                    }
                    // 过滤空行
                    if (!$row['title']) {
                        continue;
                    }
                    // 特殊字段处理
                    foreach ($row as $key => $item) {
                        if ($key == 'kind') {
                            switch ($item) {
                                case '判断':
                                case '判断题':
                                    $item = 'JUDGE';
                                    break;
                                case '单选':
                                case '单选题':
                                    $item = 'SINGLE';
                                    break;
                                case '多选':
                                case '多选题':
                                    $item = 'MULTI';
                                    break;
                                case '填空':
                                case '填空题':
                                    $item = 'FILL';
                                    break;
                                case '简答':
                                case '简答题':
                                    $item = 'SHORT';
                                    break;
                            }
                        } else if ($key == 'difficulty') {
                            switch ($item) {
                                case '低':
                                case '简单':
                                    $item = 'EASY';
                                    break;
                                case '高':
                                case '困难':
                                    $item = 'HARD';
                                    break;
                                default:
                                    $item = 'GENERAL';
                                    break;
                            }
                        }
                        $row[$key] = $item;
                    }

                    // 判断题特殊情况处理
                    if ($row['kind'] == 'JUDGE') {
                        switch ($row['answer']) {
                            case '正确':
                            case '对':
                                $row['answer'] = 'A';
                                break;
                            case '错误':
                            case '错':
                                $row['answer'] = 'B';
                                break;
                        }
                        $options = $options ? $options : ['A' => '正确', 'B' => '错误'];
                    }
                    // 答案特殊处理
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace('，', ',', $row['answer']);

                    if ($row['answer'] == '' || ($row['kind'] == 'MULTI' && !strpos($row['answer'], ','))) {
                        throw new \Exception('题目【' . $row['title'] . '】答案格式有误');
                    }
                    // 填空题
                    if ($row['kind'] == 'FILL') {
                        $row['answer'] = explode('|||', $row['answer']);
                        $fill_count = count(explode('______', $row['title'])) - 1;
                        $answer_count = count($row['answer']);

                        if ($fill_count != $answer_count) {
                            throw new \Exception('题目【' . $row['title'] . '】填空位与答案数量不匹配');
                        }

                        $fill_answers = [];
                        foreach ($row['answer'] as $item) {
                            $fill_answers[] = ['answers' => explode(',', $item)];
                        }

                        $row['answer'] = json_encode($fill_answers, JSON_UNESCAPED_UNICODE);
                    }
                    // 简答题
                    if ($row['kind'] == 'SHORT') {
                        $row['answer'] = explode('|||', $row['answer']);
                        if ($row['answer']) {
                            $short_answers = [
                                'answer' => $row['answer'][0],
                                'config' => [],
                            ];

                            if (isset($row['answer'][1]) && $row['answer'][1]) {
                                $keywords = explode(',', str_replace('，', ',', $row['answer'][1]));
                                foreach ($keywords as $keyword) {
                                    $short_answers['config'][] = [
                                        'answer' => $keyword,
                                        'score' => 1,
                                    ];
                                }
                            }

                            $row['answer'] = json_encode($short_answers, JSON_UNESCAPED_UNICODE);
                        }
                    }

                    $row['options_json'] = json_encode($options, JSON_UNESCAPED_UNICODE);
                    $row['mock_id'] = $mock_id;
                    $row['examination_point_ids'] = $examination_point_ids;
                    $row['weigh'] = $weigh++;
                    $row['createtime'] = $time;
                    $insert[] = $row;
                }
                print_r($insert);exit;
                Session::set('import_question', $insert);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }

            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            $this->success('识别成功', '', ['count' => count($insert)]);
        }
        $this->error('错误的提交方式');
    }


        /**
     * Account:导入页面
     * User: Ixiangang
     * Date: 2025/6/4
     * Time: 17:17
     */
    public function import()
    {
        if ($this->request->isPost()) {
            // 加载数据
            $insert = Session::pull('import_question'); //excel
            if (!$insert) {
                $this->error(__('没有可以导入的数据，请重新上传文件'));
            }
            try {
                $this->model->saveAll($insert);
            } catch (PDOException $exception) {
                $msg = $exception->getMessage();
                if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                    $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
                };
                $this->error($msg);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }
            $this->success();
        }
        $question_menu_id = $this->request->param('question_menu_id');
        $this->assign('question_menu_id',$question_menu_id);
        return $this->view->fetch();
    }



}
